package com.shigu.component.shiro.filter;

import com.alibaba.fastjson.JSONObject;
import com.shigu.component.enums.SessionEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * 登陆的用户过滤器
 */
@Service("userLoginFilter")
public class UserLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (!hasLogin()) {
            writeToResponse((HttpServletResponse) response,"{\"success\":false,\"auth\":false}");
            return;
        }
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }

    /**
     * 登陆判断
     * @return
     * @throws IOException
     */
    public boolean hasLogin() throws IOException {
        Session session = SecurityUtils.getSubject().getSession();
        Object auth=session.getAttribute(SessionEnum.LOGIN_USER.toString());
        return auth!=null;
    }

    public void writeToResponse(HttpServletResponse response,String jsonString){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");//修复post异常信息未被解析为json
        PrintWriter writer;
        try {
            writer = response.getWriter();
            writer.print(jsonString);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
